<template>
  <el-button :type="type" icon="el-icon-download" @click="handleExport(url,params,fileName)">{{ name }}</el-button>
</template>

<script>
import axios from 'axios'
export default {
  components: {},
  props: {
    url: {
      type: String,
      default: '',
      required: true
    },
    params: {
      type: Object,
      default: function() {
        return {}
      },
      required: true
    },
    fileName: {
      type: String,
      default: '文件导出',
      required: false
    },
    type: {
      type: String,
      default: 'success',
      required: false
    },
    name: {
      type: String,
      default: '导出',
      required: false
    }
  },
  data() {
    return {
      baseURL: 'http://192.168.31.45:666/api'
    }
  },
  mounted() {},
  methods: {
    handleExport(url, params, fileName) {
      axios({
        method: 'get',
        url: this.baseURL + url,
        responseType: 'blob',
        params,
        headers: { 'X-Access-Token': 'eyJ0eXAiOiJKV' }
      }).then(res => {
        const data = res.data
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      }).catch(res => {
        this.$message.error(res.message || '系统异常')
      })
    }
  }
}
</script>
<style scoped lang='less'>
</style>
